package com.wf.smartcomm.server.serviceImpl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.bean.YellowPage;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.YellowPageService;
import com.wf.smartcomm.server.util.IdUtils;

@Service
@Transactional
public class YellowPageServiceImpl implements YellowPageService {
	
	@Resource
	private SessionFactory factory;

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public YellowPage get(String id) {
		return (YellowPage) factory.getCurrentSession().get(YellowPage.class, id);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void listByVillage(Village village, Page page) {
		Query query = factory.getCurrentSession().createQuery("select count(*) from YellowPage where village =:village");
		query.setParameter("village",village);
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from YellowPage where village =:village order by updateAt desc");
		query.setParameter("village", village);
		query.setFirstResult(page.getBeginIndex());
		query.setMaxResults(page.getPageSize());
		page.setDataList(query.list());
	}

	@Override
	public void update(YellowPage yp) {
		yp.setUpdateAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().update(yp);
	}

	@Override
	public void delete(YellowPage yp) {
		factory.getCurrentSession().delete(yp);
	}

	@Override
	public void save(YellowPage yp) {
		yp.setObjectId(IdUtils.uuid());
		yp.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		yp.setUpdateAt(yp.getCreatedAt());
		factory.getCurrentSession().save(yp);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void query(Village loginVillage, String key, Page page) {
		String hql = "select count(*) from YellowPage where village =:village and name like :key";
		Query query = factory.getCurrentSession().createQuery(hql);
		query.setParameter("village", loginVillage);
		query.setParameter("key", "%"+key+"%");
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		hql = "from YellowPage where village =:village and name like :key order by updateAt desc";
		query = factory.getCurrentSession().createQuery(hql);
		query.setParameter("village", loginVillage);
		query.setParameter("key", "%"+key+"%");
		query.setFirstResult(page.getBeginIndex());
		query.setMaxResults(page.getPageSize());
		page.setDataList(query.list());
	}

}
